package middlewares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"goadmin/utils"
	"net/http"
	"strings"
)

func InitAdminAuthMiddleware(c *gin.Context) {
	//进行权限判断 没有登录的用户 不能进入后台管理中心
	authHeader := c.GetHeader("Authorization")
	if authHeader == "" {
		c.JSON(http.StatusUnauthorized, gin.H{
			"msg":  "未提供认证令牌",
			"code": 401,
		})
		c.Abort()
		return
	}
	// 2. 检查token格式 (Bearer <token>)
	parts := strings.SplitN(authHeader, " ", 2)
	fmt.Printf("解析token--->>: %+v\n", parts)
	if !(len(parts) == 2 && parts[0] == "Bearer") {
		c.JSON(http.StatusUnauthorized, gin.H{
			"msg":  "令牌格式错误",
			"code": 401,
		})
		c.Abort()
		return
	}
	fmt.Printf("解析token--->>: %+v\n", parts[1])
	// 3. 解析token
	claims, err := utils.ParseToken(parts[1])
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"msg":     "无效的令牌",
			"code":    401,
			"errInfo": err.Error(),
		})
		c.Abort()
		return
	}
	// 4. 将用户信息存入上下文
	c.Set("user_id", claims.UserID)
	c.Set("username", claims.Username)
	fmt.Printf("用户数据----claims.UserID: %+v\n", claims.UserID)
	fmt.Printf("用户数据----claims.Username: %+v\n", claims.Username)
	c.Next()
}
